// scripts/watch-and-build.js
const chokidar = require('chokidar');
const { exec } = require('child_process');

// 监听 src 目录下的所有文件变化
const watcher = chokidar.watch('src', {
  ignored: /(^|[\/\\])\../, // 忽略 .git 和 node_modules
  persistent: true
});


// 监听添加事件  
watcher.on('add', path => rebuild(path));
// 监听更改事件
watcher.on('change', path => rebuild(path));
// 监听删除事件 
watcher.on('unlink', path => rebuild(path));

function rebuild(path) {
  console.log(`File ${path} has been modified. Rebuilding...`);
  exec('npm run build', (error, stdout, stderr) => {
    if (error) {
      console.error(`Error: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`stderr: ${stderr}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
  });
}